package com.wanghua.mall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.wanghua.mall.user.entity.UserLevelEntity;
import com.wanghua.mall.user.exception.PasswordErrorException;
import com.wanghua.mall.user.exception.PhoneExistException;
import com.wanghua.mall.user.exception.UsernameExistException;
import com.wanghua.mall.user.exception.UsernameNotExistException;
import com.wanghua.mall.user.vo.GiteeUserVo;
import com.wanghua.mall.user.vo.RegisterVo;
import com.wanghua.mall.user.service.UserLevelService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanghua.common.utils.PageUtils;
import com.wanghua.common.utils.Query;

import com.wanghua.mall.user.dao.UserDao;
import com.wanghua.mall.user.entity.UserEntity;
import com.wanghua.mall.user.service.UserService;

import javax.annotation.Resource;


@Service
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Resource
    private UserLevelService userLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 用户注册
     */
    @Override
    public void register(RegisterVo registerVo) {
        //校验用户名和手机号是否重复
        checkPhoneUnique(registerVo.getPhone());
        checkUsernameUnique(registerVo.getUsername());
        //设置UserEntity
        UserEntity userEntity = new UserEntity();
        userEntity.setMobile(registerVo.getPhone());
        userEntity.setUsername(registerVo.getUsername());
        userEntity.setNickname(registerVo.getUsername());
        userEntity.setLevelId(userLevelService.getOne(new QueryWrapper<UserLevelEntity>()
                .eq("default_status", 1)).getId());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        userEntity.setPassword(passwordEncoder.encode(registerVo.getPassword()));
        baseMapper.insert(userEntity);

    }

    //检查手机号是否存在
    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer count = baseMapper.selectCount(new QueryWrapper<UserEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    //检查用户名是否存在
    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Integer count = baseMapper.selectCount(new QueryWrapper<UserEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExistException();
        }

    }

    /**
     * 用户登录
     * @return
     */
    @Override
    public UserEntity login(RegisterVo registerVo) {
        String username = registerVo.getUsername();
        String password = registerVo.getPassword();
        UserEntity userEntity = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("username", username));
        if (userEntity == null) {
            throw new UsernameNotExistException();
        }
        //校验密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(password, userEntity.getPassword())) {
            throw new PasswordErrorException();
        }
        return userEntity;
    }

    /**
     * 第三方账号登录->>Gitee
     * @return
     */
    @Override
    public UserEntity giteeLogin(String giteeUserVoJson) {
        GiteeUserVo giteeUserVo = JSON.parseObject(giteeUserVoJson, GiteeUserVo.class);
        //1、先检查该用户是否已经注册过，对于Gitee账号，其id保存为username,name保存为nickname
        UserEntity userEntity = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("username", giteeUserVo.getId().toString()));
        if (userEntity != null) {
            //2、说明该用户已经注册过，先更新一些信息，直接登陆即可
            userEntity.setAvatar(giteeUserVo.getAvatar_url());
            userEntity.setNickname(giteeUserVo.getName());
            userEntity.setEmail(giteeUserVo.getEmail());
            baseMapper.updateById(userEntity);
            return userEntity;
        }
        //2、说明该用户没有注册过，注册！
        userEntity = new UserEntity();
        userEntity.setUsername(giteeUserVo.getId().toString());
        userEntity.setAvatar(giteeUserVo.getAvatar_url());
        userEntity.setNickname(giteeUserVo.getName());
        userEntity.setEmail(giteeUserVo.getEmail());
        userEntity.setLevelId(userLevelService.getOne(new QueryWrapper<UserLevelEntity>()
                .eq("default_status", 1)).getId());
        baseMapper.insert(userEntity);
        return userEntity;
    }

}